/**
 * menkor.com Inc.
 * Copyright (c) 2012-2019 All Rights Reserved.
 */
package com.blueskykong.concurrency.thread;

import java.util.HashSet;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @author keets
 * @date 2019-10-10.
 */
public class ExecutorTest {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ExecutorService executorService = Executors.newFixedThreadPool(3, new ThreadFactory() {

            final AtomicInteger threadNumber = new AtomicInteger(1);

            public Thread newThread(Runnable runnable) {
                // Use our own naming scheme for the threads.
                Thread thread = new Thread(Thread.currentThread().getThreadGroup(), runnable,
                        "pool-spark" + threadNumber.getAndIncrement(), 0); //这里实现命名
                // Make workers daemon threads.
                thread.setDaemon(true);
                if (thread.getPriority() != Thread.NORM_PRIORITY) {
                    thread.setPriority(Thread.NORM_PRIORITY);
                }
                return thread;
            }
        });

        Set<Callable<String>> callables = new HashSet<Callable<String>>();

        callables.add(() -> {
            System.out.println(Thread.currentThread().getName());
            return "Task 1";
        });
        callables.add(() -> {
            System.out.println(Thread.currentThread().getName());
            return "Task 2";
        });
        callables.add(() -> {
            System.out.println(Thread.currentThread().getName());
            return "Task 3";
        });

        List<Future<String>> results = executorService.invokeAll(callables);


        for (Future<String> future : results) {
            System.out.println("future.get = " + future.get());
        }

        executorService.shutdown();
    }
}
